#include"SList.h"

void SLTPrint(SLTNode* phead)
{
	SLTNode* cur = phead->next;
	while (cur != NULL)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}


SLTNode* InitNode()
{
	SLTNode* phead = SLTBuyNode(-1);
	return phead;
}


void SLTPushBack(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* newnode = SLTBuyNode(x);
	SLTNode* tail = phead;
	while (tail->next != NULL)
	{
		tail = tail->next;
	}
	tail->next = newnode;
}

void SLTPushFront(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* newnode = SLTBuyNode(x);
	SLTNode* next = phead->next;
	phead->next = newnode;
	newnode->next = next;
}

void SLTPophBack(SLTNode* phead)
{
	assert(phead);
	assert(phead->next!=NULL);
	SLTNode* cur = phead;
	while (cur->next->next != NULL)
	{
		cur = cur->next;
	}

	free(cur->next);
	cur->next = NULL;
}

void SLTPopFront(SLTNode* phead)
{
	assert(phead);
	assert(phead->next != NULL);
	SLTNode* del = phead->next;
	SLTNode* next = phead->next->next;
	phead->next = next;
	free(del);
	del = NULL;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	if (phead->next == NULL) return -1;
	SLTNode* cur = phead->next;
	while (cur!= NULL)
	{
		if (cur->data == x)
		{
			return cur;
		}
		else
		{
			cur = cur->next;
		}
	}

	return -1;
}


void SLTInsert(SLTNode* phead, SLTNode* pos, SLTDataType x)//pos之前插入
{
	assert(phead);
	assert(pos);
	assert(phead != pos);
	SLTNode* newnode = SLTBuyNode(x);
	if (phead -> next == pos)
	{
		phead->next = newnode;
		newnode->next = pos;
	}
	SLTNode* cur = phead->next;
	while (cur->next!= pos)
	{
		cur = cur->next;
	}
	cur->next = newnode;
	newnode->next = pos;
}

void SLTErase(SLTNode* phead, SLTNode* pos)//pos位置删除
{
	assert(phead);
	assert(pos);
	assert(phead != pos);

	if (phead->next == pos)
	{
		phead->next = pos->next;
		free(pos);
	}
	else
	{
		SLTNode* cur = phead->next;
		while (cur->next!= pos)
		{
			cur = cur->next;
		}
		cur->next = pos->next;
		free(pos);
	}
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x)// pos后面插入
{
	assert(pos);
	SLTNode* newnode = SLTBuyNode(x);
	SLTNode* next = pos->next;
	pos->next = newnode;
	newnode->next = next;
}

void SLTEraseAfter(SLTNode* pos)// pos位置后面删除
{
	assert(pos);
	assert(pos->next);
	SLTNode* del = pos->next;
	pos->next = del->next;
	free(del);

}

void SLTDestroy(SLTNode* phead)//销毁链表
{
	assert(phead);
	SLTNode* del = phead->next;
	SLTNode* next = NULL;
	while (del->next != NULL)
	{
		next = del->next;
		free(del);
		del = next;
	}
	phead->next = NULL;
	free(phead);
	phead = NULL;
}